from myapp import models
from myapp.utils import getPublicData
from myapp.utils.error import errorResponse


def getPageData():
    educationalList = list(getPublicData.educations.keys())
    educationalList.insert(0, '')
    experienceList = getPublicData.workExperience
    experienceList.insert(0, '')
    jobList = []

    try:
        jobs = getPublicData.getAllJobs()
        works = {}
        for job in jobs:
            if works.get(job.title, -1) == -1:
                works[job.title] = 1
            else:
                continue
        jobList = list(works.keys())
        if len(jobList) > 1: jobList.insert(0, '')
        pass
    except Exception as err:
        print(f'---- err: {err}')

    return educationalList, experienceList, jobList


def changeData(request):
    username = request.session.get('username', '')
    educational = request.POST.get('educational', '')
    experience = request.POST.get('experience', '')
    address = request.POST.get('address', '')
    job = request.POST.get('work', '')
    avatar = request.FILES.get('avatar')
    print(f'--- user: {username}, job: {job}, avatar: {avatar}')

    user = models.Users.objects.filter(username=username).first()
    print(user.work)
    if not user: return errorResponse(request, '用户信息不存在！')

    try:
        user.educational = educational
        user.workEucational = experience
        user.address = address
        user.work = job
        if avatar:
            user.avatar = avatar
        user.save()
    except Exception as err:
        print(f'--- err: {err}')

    return